//
//  ClassificationViewController.m
//  HomeIn
//
//  Created by 张涛 on 15/11/6.
//  Copyright © 2015年 ZZP. All rights reserved.

#import "ClassificationViewController.h"
#import "ClassificationCollectionViewCell.h"
#import "ClassificationDetailVC.h"
#import "ClassificationModel.h"

@interface ClassificationViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
@property(nonatomic,strong)UICollectionView *classificationCollection;
@property(nonatomic,strong)NSMutableArray *allArray;
//上拉下拉刷新
@property(nonatomic,assign)NSInteger currentPage;
@property(nonatomic,assign)BOOL isUpLoading;
@property(nonatomic,strong)MBProgressHUD *hud;

@property(nonatomic,strong)NSString *cat;
@end

@implementation ClassificationViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(50*WIDTHSCALE, 0, 150*WIDTHSCALE, 44*HEIGHTSCALE)];
    titleLabel.text = @"新品";
    titleLabel.textColor = [UIColor wheatColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = [UIFont fontWithName:@"Arial" size:16];
    self.navigationItem.titleView = titleLabel;
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor wheatColor];
    //
    self.allArray = [NSMutableArray array];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    //
    flowLayout.itemSize = CGSizeMake(360 * WIDTHSCALE, 235 *HEIGHTSCALE);
    flowLayout.sectionInset = UIEdgeInsetsMake(5 *WIDTHSCALE , 5 *HEIGHTSCALE, 5, 5);
    //列间距
    flowLayout.minimumInteritemSpacing = 5;
    //行间距
    flowLayout.minimumLineSpacing = 5;
    //竖向滑动
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    self.classificationCollection = [[UICollectionView alloc]initWithFrame:BOUNDS collectionViewLayout:flowLayout];
    self.classificationCollection.delegate = self;
    self.classificationCollection.dataSource = self;
    self.classificationCollection.backgroundColor = [UIColor wheatColor];
    [self.view addSubview:self.classificationCollection];
    
    //注册 cell
    [self.classificationCollection registerClass:[ClassificationCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    [self refreshMB];
    [self.classificationCollection reloadData];
}
//
-(void)refreshMB
{
    self.cat = @"more";
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.hud show:YES];
    self.hud.labelText = @"正在帮你加载...";
    self.currentPage = 0;
    self.isUpLoading = NO;

    //下拉刷新
    [self addHeadRefresh];
    //上拉刷新
    [self addFoodRefresh];
}
-(void)hudWasHidden:(MBProgressHUD *)hud
{
    [hud removeFromSuperview];
    hud = nil;
}
-(void)addHeadRefresh
{
    
    if ([self.cat isEqualToString:@"more"])
    {
        __block ClassificationViewController *VC = self;
        //
        self.classificationCollection.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            VC.currentPage = 1;
            VC.isUpLoading = NO;
            [VC AFNWorking:VC.currentPage];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [VC.classificationCollection reloadData];
                self.hud.hidden = YES;
            });
            
        }];
        //马上进入刷新状态
        [self.classificationCollection.header beginRefreshing];

    }
    else
    {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"已经到最后页面!" delegate: self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
    }
    
}
//
-(void)addFoodRefresh
{
    __block ClassificationViewController *VC = self;
    self.classificationCollection.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        VC.currentPage++;
        VC.isUpLoading = YES;
        [VC AFNWorking:VC.currentPage];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [VC.classificationCollection reloadData];
            self.hud.hidden = YES;
        });
        
    }];
}

-(void)AFNWorking:(NSInteger)page
{
    if ([self.cat isEqualToString:@"more"])
    {
        NSString *url_string = [NSString stringWithFormat:@"http://buy.zhaidou.com/?zdclient=ios&tag=006&json=1&count=10&page=%ld",page];
        //
        [BlockGetAFNYiBu GetAfnURLWithString:url_string resultBlock:^(id result)
         {
            NSMutableDictionary *bigDic = (NSMutableDictionary *)result;
            
            if (!self.isUpLoading)
            {
                [self.allArray removeAllObjects];
            }
            NSMutableArray *array = [bigDic objectForKey:@"posts"];
            for (NSMutableDictionary *smallDic in array)
            {
                ClassificationModel *model = [[ClassificationModel alloc]init];
               [model setValuesForKeysWithDictionary:smallDic];
                
                model = [smallDic objectForKey:@"thumbanail"];
                model = [smallDic objectForKey:@"title"];
                model = [smallDic objectForKey:@"url"];
               
                [self.allArray addObject:model];

                
            }
             
            //刷新数据
            [self.classificationCollection reloadData];
            self.hud.hidden=YES;
            
            //结束刷新
            [self.classificationCollection.header endRefreshing];
            [self.classificationCollection.footer endRefreshing];
            [self hudWasHidden: self.hud];
        } errorBlcok:^(NSError *error) {
            //网络环境
            [self refurbishBaulk];
            
        }];
    }else
    {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"已经到最后页面!" delegate: self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
        
    }
    
    
}
-(void)refurbishBaulk
{
    UIAlertView *aView=[[UIAlertView alloc]initWithTitle:@"刷新失败" message:@"请检查网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [aView show];

}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.allArray.count;

}
//
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ClassificationCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor wheatColor];
    ClassificationModel *model = [self.allArray objectAtIndex:indexPath.row];
    cell.model = model;
    return cell;
}
//cell点击事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    //取消点击效果
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    ClassificationModel *model = [self.allArray objectAtIndex:indexPath.row];
    ClassificationDetailVC *detailVC = [[ClassificationDetailVC alloc]init];
    //需用属性将拼接model传送到下一个页面
    detailVC.model = model;
    detailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detailVC animated:YES];

}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    return CGSizeMake(360 * WIDTHSCALE, 235 * HEIGHTSCALE);
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
